package cn.hyatt.auth.service.impl;

import cn.hyatt.auth.dto.auth.AuthInfo;
import cn.hyatt.auth.service.AuthCacheService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Optional;

/**
 * 身份验证缓存服务-实现
 *
 * @author hyatt
 */
@Slf4j
@Service
@Primary
@AllArgsConstructor
public class AuthCacheServiceImpl implements AuthCacheService {
    // 验证码Key
    private static final String CAPTCHA_KEY = "system:captcha:";
    // TokenKey
    private static final String TOKEN_KEY = "system:token:";
    private RedissonClient redissonClient;

    /**
     * 获取验证码
     *
     * @param request HTTP 请求
     * @return 结果
     */
    @Override
    public Optional<String> getCaptcha(HttpServletRequest request) {
        // 获取请求用户Session信息
        HttpSession session = request.getSession();
        String sessionId = session.getId();
        RBucket<String> bucket = redissonClient.getBucket(CAPTCHA_KEY + sessionId);
        if (bucket.isExists()) {
            return Optional.of(bucket.get());
        }
        return Optional.empty();

    }

    /**
     * 保存 captcha
     *
     * @param sessionId sessionId
     * @param captcha   验证码
     */
    @Override
    public void saveCaptcha(String sessionId, String captcha) {
        // 保存验证码至Redis缓存，有效期为5分钟
        RBucket<String> bucket = redissonClient.getBucket(CAPTCHA_KEY + sessionId);
        bucket.set(captcha, Duration.ofMinutes(5));
    }

    /**
     * 获取认证信息
     *
     * @param userId 用户Id
     * @return 结果
     */
    @Override
    public Optional<AuthInfo> getAuthInfo(Long userId) {
        // 获取请求用户Session信息
        RBucket<AuthInfo> bucket = redissonClient.getBucket(TOKEN_KEY + userId);
        if (bucket.isExists()) {
            return Optional.of(bucket.get());
        }
        return Optional.empty();

    }

    /**
     * 保存认证信息
     *
     * @param userId   用户Id
     * @param authInfo 认证信息
     */
    @Override
    public void saveAuthInfo(Long userId, AuthInfo authInfo) {
        // 保存Token至Redis缓存，有效期为60分钟
        RBucket<AuthInfo> bucket = redissonClient.getBucket(TOKEN_KEY + userId);
        bucket.set(authInfo, Duration.ofMinutes(60));
    }

}
